<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>English Posts Platform</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3a0ca3;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
            --warning-color: #f8961e;
            --admin-color: #ff6b6b;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f5f7fb;
            color: var(--dark-color);
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 1.5rem 0;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            font-size: 1.8rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .user-role {
            background: rgba(255, 255, 255, 0.2);
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.9rem;
        }
        
        .admin-badge {
            background-color: var(--admin-color);
        }
        
        .login-section {
            display: flex;
            gap: 10px;
        }
        
        .login-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .login-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .admin-login-btn {
            background: var(--admin-color);
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 2rem;
            margin: 2rem 0;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
        
        .post-form {
            background-color: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            position: sticky;
            top: 20px;
        }
        
        .form-group {
            margin-bottom: 1.2rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
        }
        
        textarea.form-control {
            min-height: 150px;
            resize: vertical;
        }
        
        .btn {
            display: inline-block;
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 0.8rem 1.5rem;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn:hover {
            background-color: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .btn-danger {
            background-color: var(--danger-color);
        }
        
        .btn-danger:hover {
            background-color: #d1144a;
        }
        
        .btn-admin {
            background-color: var(--admin-color);
        }
        
        .btn-admin:hover {
            background-color: #ff5252;
        }
        
        .posts-section {
            background-color: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }
        
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 0.8rem;
            border-bottom: 1px solid #eee;
        }
        
        .section-title {
            font-size: 1.5rem;
            font-weight: 600;
        }
        
        .search-box {
            display: flex;
        }
        
        .search-box input {
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 5px 0 0 5px;
            width: 200px;
        }
        
        .search-box button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0 5px 5px 0;
            cursor: pointer;
        }
        
        .post {
            border-bottom: 1px solid #eee;
            padding: 1.2rem 0;
            position: relative;
        }
        
        .post:last-child {
            border-bottom: none;
        }
        
        .post-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.8rem;
        }
        
        .post-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--dark-color);
        }
        
        .post-date {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .post-content {
            margin-bottom: 1rem;
            line-height: 1.6;
            white-space: pre-line;
        }
        
        .post-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .post-author {
            font-weight: 500;
            color: var(--primary-color);
        }
        
        .post-actions button {
            background: none;
            border: none;
            color: #6c757d;
            cursor: pointer;
            margin-left: 1rem;
            transition: color 0.3s;
        }
        
        .post-actions button:hover {
            color: var(--primary-color);
        }
        
        .like-btn.liked {
            color: var(--primary-color);
        }
        
        .char-count {
            text-align: right;
            font-size: 0.8rem;
            color: #6c757d;
            margin-top: 0.3rem;
        }
        
        footer {
            background-color: var(--dark-color);
            color: white;
            text-align: center;
            padding: 1.5rem 0;
            margin-top: 2rem;
        }
        
        .empty-posts {
            text-align: center;
            padding: 2rem;
            color: #6c757d;
        }
        
        .empty-posts i {
            font-size: 3rem;
            margin-bottom: 1rem;
            display: block;
            color: #dee2e6;
        }
        
        .delete-btn {
            position: absolute;
            top: 1rem;
            right: 0;
            background: none;
            border: none;
            color: #dc3545;
            cursor: pointer;
            font-size: 1.2rem;
            opacity: 0.7;
            transition: opacity 0.3s;
        }
        
        .delete-btn:hover {
            opacity: 1;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 1rem 1.5rem;
            border-radius: 5px;
            color: white;
            font-weight: 500;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            transform: translateX(150%);
            transition: transform 0.3s ease-in-out;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification.success {
            background-color: var(--success-color);
        }
        
        .notification.error {
            background-color: var(--danger-color);
        }
        
        .stats {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .stat-box {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 1rem;
            border-radius: 8px;
            text-align: center;
            flex: 1;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
        }
        
        .stat-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .admin-panel {
            background-color: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            margin-bottom: 2rem;
            border-left: 5px solid var(--admin-color);
        }
        
        .admin-panel h2 {
            color: var(--admin-color);
            margin-bottom: 1rem;
        }
        
        .admin-controls {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 2000;
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background-color: white;
            padding: 2rem;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }
        
        .modal h2 {
            margin-bottom: 1rem;
            color: var(--primary-color);
        }
        
        .modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 1.5rem;
        }
        
        .auth-tabs {
            display: flex;
            margin-bottom: 1.5rem;
            border-bottom: 1px solid #ddd;
        }
        
        .auth-tab {
            padding: 0.8rem 1.5rem;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .auth-tab.active {
            color: var(--primary-color);
            border-bottom: 3px solid var(--primary-color);
        }
        
        .auth-form {
            display: none;
        }
        
        .auth-form.active {
            display: block;
        }
        
        .post-author-input {
            display: none;
        }
        
        .admin-login-section {
            text-align: center;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #eee;
        }
        
        .users-list {
            margin-top: 1.5rem;
        }
        
        .user-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.8rem;
            border-bottom: 1px solid #eee;
        }
        
        .user-item:last-child {
            border-bottom: none;
        }
        
        .user-info-small {
            display: flex;
            flex-direction: column;
        }
        
        .user-name {
            font-weight: 500;
        }
        
        .user-username {
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .user-stats {
            font-size: 0.8rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <div class="header-content">
                <div class="logo">
                    <i class="fas fa-pen-nib"></i>
                    EnglishPosts
                </div>
                <div id="userInfo" class="user-info" style="display: none;">
                    <span>Welcome, <span id="userName">User</span></span>
                    <span id="userRole" class="user-role">User</span>
                    <button id="logoutBtn" class="login-btn">Logout</button>
                </div>
                <div id="loginSection" class="login-section">
                    <button id="showAuthModal" class="login-btn">Login / Register</button>
                    <button id="adminLoginBtn" class="login-btn admin-login-btn">Admin Login</button>
                </div>
            </div>
        </div>
    </header>
    
    <div class="container">
        <div id="adminPanel" class="admin-panel" style="display: none;">
            <h2><i class="fas fa-shield-alt"></i> Administrator Panel</h2>
            <div class="admin-controls">
                <button id="clearAllBtn" class="btn btn-admin"><i class="fas fa-trash"></i> Clear All Posts</button>
                <button id="viewStatsBtn" class="btn btn-admin"><i class="fas fa-chart-bar"></i> View Statistics</button>
                <button id="exportDataBtn" class="btn btn-admin"><i class="fas fa-download"></i> Export Data</button>
                <button id="manageUsersBtn" class="btn btn-admin"><i class="fas fa-users"></i> Manage Users</button>
            </div>
            
            <div id="usersManagement" class="users-list" style="display: none; margin-top: 1.5rem;">
                <h3><i class="fas fa-users-cog"></i> User Management</h3>
                <div id="usersList">
                    <!-- Users will be listed here -->
                </div>
            </div>
        </div>
        
        <div class="stats">
            <div class="stat-box">
                <div class="stat-number" id="totalPosts">0</div>
                <div class="stat-label">Total Posts</div>
            </div>
            <div class="stat-box">
                <div class="stat-number" id="todayPosts">0</div>
                <div class="stat-label">Today's Posts</div>
            </div>
            <div class="stat-box">
                <div class="stat-number" id="totalChars">0</div>
                <div class="stat-label">Total Characters</div>
            </div>
        </div>
        
        <div class="main-content">
            <section class="post-form">
                <h2><i class="fas fa-edit"></i> Create New Post</h2>
                <form id="postForm">
                    <div class="form-group">
                        <label for="postTitle">Title</label>
                        <input type="text" id="postTitle" class="form-control" placeholder="Enter post title" required>
                    </div>
                    <div class="form-group">
                        <label for="postContent">Content</label>
                        <textarea id="postContent" class="form-control" placeholder="Write your post in English..." required></textarea>
                        <div class="char-count"><span id="charCount">0</span>/500 characters</div>
                    </div>
                    <div class="form-group post-author-input">
                        <label for="postAuthor">Author Name</label>
                        <input type="text" id="postAuthor" class="form-control" placeholder="Your name">
                    </div>
                    <button type="submit" class="btn"><i class="fas fa-paper-plane"></i> Publish Post</button>
                </form>
            </section>
            
            <section class="posts-section">
                <div class="section-header">
                    <h2 class="section-title"><i class="fas fa-list"></i> Recent Posts</h2>
                    <div class="search-box">
                        <input type="text" id="searchInput" placeholder="Search posts...">
                        <button id="searchBtn"><i class="fas fa-search"></i></button>
                    </div>
                </div>
                
                <div id="postsContainer">
                    <!-- Posts will be dynamically added here -->
                    <div class="empty-posts">
                        <i class="fas fa-sticky-note"></i>
                        <p>No posts yet. Be the first to share your thoughts!</p>
                    </div>
                </div>
            </section>
        </div>
    </div>
    
    <footer>
        <div class="container">
            <p>&copy; 2023 EnglishPosts. All rights reserved.</p>
        </div>
    </footer>
    
    <!-- Auth Modal -->
    <div id="authModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-user"></i> Welcome to EnglishPosts</h2>
            <div class="auth-tabs">
                <button class="auth-tab active" data-tab="login">Login</button>
                <button class="auth-tab" data-tab="register">Register</button>
            </div>
            
            <form id="loginForm" class="auth-form active">
                <div class="form-group">
                    <label for="loginUsername">Username</label>
                    <input type="text" id="loginUsername" class="form-control" placeholder="Enter your username" required>
                </div>
                <div class="form-group">
                    <label for="loginPassword">Password</label>
                    <input type="password" id="loginPassword" class="form-control" placeholder="Enter your password" required>
                </div>
                <div class="modal-actions">
                    <button type="button" id="cancelAuth" class="btn">Cancel</button>
                    <button type="submit" class="btn">Login</button>
                </div>
            </form>
            
            <form id="registerForm" class="auth-form">
                <div class="form-group">
                    <label for="registerUsername">Username</label>
                    <input type="text" id="registerUsername" class="form-control" placeholder="Choose a username" required>
                </div>
                <div class="form-group">
                    <label for="registerPassword">Password</label>
                    <input type="password" id="registerPassword" class="form-control" placeholder="Choose a password" required>
                </div>
                <div class="form-group">
                    <label for="registerName">Display Name</label>
                    <input type="text" id="registerName" class="form-control" placeholder="Your display name" required>
                </div>
                <div class="modal-actions">
                    <button type="button" id="cancelRegister" class="btn">Cancel</button>
                    <button type="submit" class="btn">Register</button>
                </div>
            </form>
            
            <div class="admin-login-section">
                <p>Are you an administrator?</p>
                <button id="adminLoginFromAuth" class="btn btn-admin">Admin Login</button>
            </div>
        </div>
    </div>
    
    <!-- Admin Login Modal -->
    <div id="adminLoginModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-shield-alt"></i> Admin Login</h2>
            <div class="form-group">
                <label for="adminPassword">Admin Password</label>
                <input type="password" id="adminPassword" class="form-control" placeholder="Enter admin password" required>
            </div>
            <div class="modal-actions">
                <button id="cancelAdminLogin" class="btn">Cancel</button>
                <button id="confirmAdminLogin" class="btn btn-admin">Login</button>
            </div>
        </div>
    </div>
    
    <!-- Clear All Posts Modal -->
    <div id="clearPostsModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-exclamation-triangle"></i> Confirm Action</h2>
            <p>Are you sure you want to delete all posts? This action cannot be undone.</p>
            <div class="modal-actions">
                <button id="cancelClearPosts" class="btn">Cancel</button>
                <button id="confirmClearPosts" class="btn btn-danger">Delete All Posts</button>
            </div>
        </div>
    </div>
    
    <!-- Delete Post Modal -->
    <div id="deletePostModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-exclamation-triangle"></i> Confirm Deletion</h2>
            <p>Are you sure you want to delete this post?</p>
            <div class="modal-actions">
                <button id="cancelDeletePost" class="btn">Cancel</button>
                <button id="confirmDeletePost" class="btn btn-danger">Delete Post</button>
            </div>
        </div>
    </div>
    
    <!-- Delete User Modal -->
    <div id="deleteUserModal" class="modal">
        <div class="modal-content">
            <h2><i class="fas fa-exclamation-triangle"></i> Confirm User Deletion</h2>
            <p id="deleteUserMessage">Are you sure you want to delete this user?</p>
            <div class="modal-actions">
                <button id="cancelDeleteUser" class="btn">Cancel</button>
                <button id="confirmDeleteUser" class="btn btn-danger">Delete User</button>
            </div>
        </div>
    </div>
    
    <div id="notification" class="notification"></div>
    
    <script>
        // DOM elements
        const postForm = document.getElementById('postForm');
        const postTitle = document.getElementById('postTitle');
        const postContent = document.getElementById('postContent');
        const postAuthor = document.getElementById('postAuthor');
        const charCount = document.getElementById('charCount');
        const postsContainer = document.getElementById('postsContainer');
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const notification = document.getElementById('notification');
        const totalPostsEl = document.getElementById('totalPosts');
        const todayPostsEl = document.getElementById('todayPosts');
        const totalCharsEl = document.getElementById('totalChars');
        const userInfo = document.getElementById('userInfo');
        const loginSection = document.getElementById('loginSection');
        const userName = document.getElementById('userName');
        const userRole = document.getElementById('userRole');
        const logoutBtn = document.getElementById('logoutBtn');
        const showAuthModal = document.getElementById('showAuthModal');
        const adminLoginBtn = document.getElementById('adminLoginBtn');
        const adminPanel = document.getElementById('adminPanel');
        const clearAllBtn = document.getElementById('clearAllBtn');
        const viewStatsBtn = document.getElementById('viewStatsBtn');
        const exportDataBtn = document.getElementById('exportDataBtn');
        const manageUsersBtn = document.getElementById('manageUsersBtn');
        const usersManagement = document.getElementById('usersManagement');
        const usersList = document.getElementById('usersList');
        const authModal = document.getElementById('authModal');
        const authTabs = document.querySelectorAll('.auth-tab');
        const loginForm = document.getElementById('loginForm');
        const registerForm = document.getElementById('registerForm');
        const loginUsername = document.getElementById('loginUsername');
        const loginPassword = document.getElementById('loginPassword');
        const registerUsername = document.getElementById('registerUsername');
        const registerPassword = document.getElementById('registerPassword');
        const registerName = document.getElementById('registerName');
        const cancelAuth = document.getElementById('cancelAuth');
        const cancelRegister = document.getElementById('cancelRegister');
        const adminLoginFromAuth = document.getElementById('adminLoginFromAuth');
        const adminLoginModal = document.getElementById('adminLoginModal');
        const adminPassword = document.getElementById('adminPassword');
        const cancelAdminLogin = document.getElementById('cancelAdminLogin');
        const confirmAdminLogin = document.getElementById('confirmAdminLogin');
        const clearPostsModal = document.getElementById('clearPostsModal');
        const cancelClearPosts = document.getElementById('cancelClearPosts');
        const confirmClearPosts = document.getElementById('confirmClearPosts');
        const deletePostModal = document.getElementById('deletePostModal');
        const cancelDeletePost = document.getElementById('cancelDeletePost');
        const confirmDeletePost = document.getElementById('confirmDeletePost');
        const deleteUserModal = document.getElementById('deleteUserModal');
        const deleteUserMessage = document.getElementById('deleteUserMessage');
        const cancelDeleteUser = document.getElementById('cancelDeleteUser');
        const confirmDeleteUser = document.getElementById('confirmDeleteUser');
        
        // Application state
        let posts = [];
        let currentUser = null;
        let isAdmin = false;
        let users = [];
        let postToDelete = null;
        let userToDelete = null;
        const ADMIN_PASSWORD = "admin123"; // 管理员密码
        
        // -------------------------- IndexedDB 工具函数 --------------------------
        const DB_NAME = 'EnglishPostsDB';
        const DB_VERSION = 1;
        const STORE_NAMES = {
            POSTS: 'posts',
            USERS: 'users'
        };

        // 打开数据库连接
        function openDB() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open(DB_NAME, DB_VERSION);

                // 数据库升级（首次创建或版本更新时触发）
                request.onupgradeneeded = (e) => {
                    const db = e.target.result;
                    // 创建帖子存储库（主键为id）
                    if (!db.objectStoreNames.contains(STORE_NAMES.POSTS)) {
                        db.createObjectStore(STORE_NAMES.POSTS, { keyPath: 'id', autoIncrement: false });
                    }
                    // 创建用户存储库（主键为id）
                    if (!db.objectStoreNames.contains(STORE_NAMES.USERS)) {
                        db.createObjectStore(STORE_NAMES.USERS, { keyPath: 'id', autoIncrement: false });
                    }
                };

                // 打开成功
                request.onsuccess = (e) => {
                    resolve(e.target.result);
                };

                // 打开失败
                request.onerror = (e) => {
                    reject(`IndexedDB 打开失败: ${e.target.error.message}`);
                };
            });
        }

        // 向指定存储库添加/更新数据
        function saveToDB(storeName, data) {
            return new Promise(async (resolve, reject) => {
                const db = await openDB();
                const transaction = db.transaction(storeName, 'readwrite');
                const store = transaction.objectStore(storeName);
                const request = store.put(data); // put：存在则更新，不存在则添加

                request.onsuccess = () => {
                    db.close();
                    resolve(true);
                };

                request.onerror = (e) => {
                    db.close();
                    reject(`数据保存失败: ${e.target.error.message}`);
                };
            });
        }

        // 从指定存储库获取所有数据
        function getAllFromDB(storeName) {
            return new Promise(async (resolve, reject) => {
                const db = await openDB();
                const transaction = db.transaction(storeName, 'readonly');
                const store = transaction.objectStore(storeName);
                const request = store.getAll();

                request.onsuccess = (e) => {
                    db.close();
                    resolve(e.target.result || []);
                };

                request.onerror = (e) => {
                    db.close();
                    reject(`数据获取失败: ${e.target.error.message}`);
                };
            });
        }

        // 从指定存储库删除指定id的数据
        function deleteFromDB(storeName, id) {
            return new Promise(async (resolve, reject) => {
                const db = await openDB();
                const transaction = db.transaction(storeName, 'readwrite');
                const store = transaction.objectStore(storeName);
                const request = store.delete(id);

                request.onsuccess = () => {
                    db.close();
                    resolve(true);
                };

                request.onerror = (e) => {
                    db.close();
                    reject(`数据删除失败: ${e.target.error.message}`);
                };
            });
        }

        // 清空指定存储库所有数据
        function clearDB(storeName) {
            return new Promise(async (resolve, reject) => {
                const db = await openDB();
                const transaction = db.transaction(storeName, 'readwrite');
                const store = transaction.objectStore(storeName);
                const request = store.clear();

                request.onsuccess = () => {
                    db.close();
                    resolve(true);
                };

                request.onerror = (e) => {
                    db.close();
                    reject(`数据清空失败: ${e.target.error.message}`);
                };
            });
        }

        // -------------------------- 数据存储函数 --------------------------
        // 保存帖子到 IndexedDB
        async function savePosts() {
            try {
                // 清空旧帖子，再批量保存新帖子（确保数据同步）
                await clearDB(STORE_NAMES.POSTS);
                for (const post of posts) {
                    await saveToDB(STORE_NAMES.POSTS, post);
                }
            } catch (err) {
                showNotification(`帖子保存失败: ${err}`, 'error');
            }
        }

        // 保存用户到 IndexedDB
        async function saveUsers() {
            try {
                // 清空旧用户，再批量保存新用户（确保数据同步）
                await clearDB(STORE_NAMES.USERS);
                for (const user of users) {
                    await saveToDB(STORE_NAMES.USERS, user);
                }
            } catch (err) {
                showNotification(`用户保存失败: ${err}`, 'error');
            }
        }

        // 从 IndexedDB 加载数据
        async function loadData() {
            try {
                // 加载帖子
                const savedPosts = await getAllFromDB(STORE_NAMES.POSTS);
                // 加载用户
                const savedUsers = await getAllFromDB(STORE_NAMES.USERS);

                posts = savedPosts.length ? savedPosts : [];
                users = savedUsers.length ? savedUsers : [];

                // 首次加载时添加示例数据
                if (posts.length === 0 && users.length === 0) {
                    // 示例用户
                    const sampleUsers = [
                        { id: 'admin', username: 'admin', password: 'admin123', name: 'Administrator', role: 'admin' },
                        { id: 'user1', username: 'john', password: 'password123', name: 'John Doe', role: 'user' },
                        { id: 'user2', username: 'sarah', password: 'password123', name: 'Sarah Wilson', role: 'user' }
                    ];
                    // 示例帖子
                    const samplePosts = [
                        {
                            id: 1,
                            title: 'Welcome to EnglishPosts!',
                            content: 'This is a platform where you can share your thoughts, ideas, and experiences in English. Feel free to write about anything that interests you - from daily life to profound insights. Remember to be respectful and kind to other members of our community.',
                            author: 'Admin',
                            date: new Date().toISOString(),
                            likes: 5,
                            likedBy: ['admin', 'user1', 'user2', 'user3', 'user4'],
                            userId: 'admin'
                        },
                        {
                            id: 2,
                            title: 'The Importance of Practicing English Daily',
                            content: 'Consistency is key when learning a new language. Even just 15 minutes of English practice every day can significantly improve your skills over time. Try reading a short article, writing a few sentences, or having a simple conversation in English daily.',
                            author: 'Language Learner',
                            date: new Date(Date.now() - 86400000).toISOString(), // Yesterday
                            likes: 3,
                            likedBy: ['user1', 'user2', 'user3'],
                            userId: 'user1'
                        }
                    ];

                    posts = samplePosts;
                    users = sampleUsers;

                    // 保存示例数据到数据库
                    await savePosts();
                    await saveUsers();
                }
            } catch (err) {
                showNotification(`数据加载失败: ${err}`, 'error');
                // 加载失败时用空数据兜底
                posts = [];
                users = [];
            }
        }

        // -------------------------- 交互逻辑 --------------------------
        // 字符计数
        postContent.addEventListener('input', function() {
            charCount.textContent = this.value.length;
            
            if (this.value.length > 500) {
                charCount.style.color = 'red';
            } else {
                charCount.style.color = '#6c757d';
            }
        });

        // 发布帖子
        postForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 检查用户是否登录
            if (!currentUser) {
                showNotification('Please login to create a post', 'error');
                return;
            }
            
            // 验证表单
            if (postTitle.value.trim() === '' || 
                postContent.value.trim() === '') {
                showNotification('Please fill in all fields', 'error');
                return;
            }
            
            if (postContent.value.length > 500) {
                showNotification('Post content cannot exceed 500 characters', 'error');
                return;
            }
            
            // 创建新帖子
            const newPost = {
                id: Date.now(), // 基于时间戳的唯一ID
                title: postTitle.value,
                content: postContent.value,
                author: currentUser.name,
                date: new Date().toISOString(),
                likes: 0,
                likedBy: [], // 记录点赞用户
                userId: currentUser.id
            };
            
            // 添加到帖子数组
            posts.unshift(newPost);
            await savePosts(); // 保存到IndexedDB
            
            // 更新UI
            renderPosts();
            updateStats();
            
            // 显示成功消息
            showNotification('Post published successfully!', 'success');
            
            // 重置表单
            postForm.reset();
            charCount.textContent = '0';
            charCount.style.color = '#6c757d';
        });

        // 搜索功能
        searchBtn.addEventListener('click', function() {
            const searchTerm = searchInput.value.toLowerCase().trim();
            if (searchTerm) {
                const filteredPosts = posts.filter(post => 
                    post.title.toLowerCase().includes(searchTerm) || 
                    post.content.toLowerCase().includes(searchTerm) ||
                    post.author.toLowerCase().includes(searchTerm)
                );
                renderPosts(filteredPosts);
            } else {
                renderPosts();
            }
        });

        searchInput.addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                searchBtn.click();
            }
        });

        // 登录/注册模态框
        showAuthModal.addEventListener('click', function() {
            authModal.style.display = 'flex';
        });

        // 管理员登录按钮
        adminLoginBtn.addEventListener('click', function() {
            adminLoginModal.style.display = 'flex';
        });

        adminLoginFromAuth.addEventListener('click', function() {
            authModal.style.display = 'none';
            adminLoginModal.style.display = 'flex';
        });

        // 登录/注册标签切换
        authTabs.forEach(tab => {
            tab.addEventListener('click', function() {
                const tabName = this.getAttribute('data-tab');
                
                // 更新激活标签
                authTabs.forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                
                // 显示对应表单
                document.querySelectorAll('.auth-form').forEach(form => {
                    form.classList.remove('active');
                });
                document.getElementById(tabName + 'Form').classList.add('active');
            });
        });

        // 登录表单
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const username = loginUsername.value.trim();
            const password = loginPassword.value;
            
            // 查找用户
            const user = users.find(u => u.username === username && u.password === password);
            
            if (user) {
                currentUser = user;
                isAdmin = user.role === 'admin';
                authModal.style.display = 'none';
                loginForm.reset();
                updateUserInterface();
                renderPosts(); // 重新渲染帖子以显示删除按钮
                showNotification(`Welcome back, ${user.name}!`, 'success');
            } else {
                showNotification('Invalid username or password', 'error');
            }
        });

        // 注册表单
        registerForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const username = registerUsername.value.trim();
            const password = registerPassword.value;
            const name = registerName.value.trim();
            
            // 检查用户名是否已存在
            if (users.find(u => u.username === username)) {
                showNotification('Username already exists', 'error');
                return;
            }
            
            // 创建新用户
            const newUser = {
                id: Date.now().toString(),
                username: username,
                password: password,
                name: name,
                role: 'user'
            };
            
            users.push(newUser);
            await saveUsers();
            
            currentUser = newUser;
            isAdmin = false;
            authModal.style.display = 'none';
            registerForm.reset();
            updateUserInterface();
            renderPosts(); // 重新渲染帖子
            showNotification(`Account created successfully! Welcome, ${name}!`, 'success');
        });

        // 取消登录/注册
        cancelAuth.addEventListener('click', function() {
            authModal.style.display = 'none';
            loginForm.reset();
        });

        cancelRegister.addEventListener('click', function() {
            authModal.style.display = 'none';
            registerForm.reset();
        });

        // 管理员登录模态框
        cancelAdminLogin.addEventListener('click', function() {
            adminLoginModal.style.display = 'none';
            adminPassword.value = '';
        });

        confirmAdminLogin.addEventListener('click', async function() {
            const password = adminPassword.value;
            if (password === ADMIN_PASSWORD) {
                // 检查管理员用户是否存在，不存在则创建
                let adminUser = users.find(u => u.username === 'admin');
                if (!adminUser) {
                    adminUser = {
                        id: 'admin',
                        username: 'admin',
                        password: ADMIN_PASSWORD,
                        name: 'Administrator',
                        role: 'admin'
                    };
                    users.push(adminUser);
                    await saveUsers();
                }
                
                currentUser = adminUser;
                isAdmin = true;
                adminLoginModal.style.display = 'none';
                adminPassword.value = '';
                updateUserInterface();
                renderPosts(); // 重新渲染帖子以显示删除按钮
                showNotification('Admin login successful!', 'success');
            } else {
                showNotification('Incorrect admin password', 'error');
            }
        });

        // 管理员密码输入回车登录
        adminPassword.addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                confirmAdminLogin.click();
            }
        });

        // 登出
        logoutBtn.addEventListener('click', function() {
            currentUser = null;
            isAdmin = false;
            updateUserInterface();
            renderPosts(); // 重新渲染帖子以隐藏删除按钮
            showNotification('Logged out successfully', 'success');
        });

        // 管理员功能
        clearAllBtn.addEventListener('click', function() {
            clearPostsModal.style.display = 'flex';
        });

        cancelClearPosts.addEventListener('click', function() {
            clearPostsModal.style.display = 'none';
        });

        confirmClearPosts.addEventListener('click', async function() {
            posts = [];
            await savePosts();
            renderPosts();
            updateStats();
            clearPostsModal.style.display = 'none';
            showNotification('All posts have been deleted', 'success');
        });

        viewStatsBtn.addEventListener('click', function() {
            const totalPosts = posts.length;
            const today = new Date().toDateString();
            const todayPosts = posts.filter(post => 
                new Date(post.date).toDateString() === today
            ).length;
            const totalChars = posts.reduce((total, post) => 
                total + post.content.length, 0
            );
            
            alert(`Statistics:\n\nTotal Posts: ${totalPosts}\nToday's Posts: ${todayPosts}\nTotal Characters: ${totalChars}\nTotal Users: ${users.length}`);
        });

        exportDataBtn.addEventListener('click', function() {
            const dataStr = JSON.stringify(posts, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'english_posts_export.json';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            showNotification('Data exported successfully', 'success');
        });

        // 管理用户
        manageUsersBtn.addEventListener('click', function() {
            if (usersManagement.style.display === 'none') {
                usersManagement.style.display = 'block';
                renderUsersList();
            } else {
                usersManagement.style.display = 'none';
            }
        });

        // 渲染用户列表
        function renderUsersList() {
            usersList.innerHTML = '';
            
            users.forEach(user => {
                if (user.role !== 'admin') { // 不显示管理员的删除按钮
                    const userPosts = posts.filter(post => post.userId === user.id).length;
                    const userElement = document.createElement('div');
                    userElement.className = 'user-item';
                    userElement.innerHTML = `
                        <div class="user-info-small">
                            <div class="user-name">${escapeHtml(user.name)}</div>
                            <div class="user-username">@${escapeHtml(user.username)}</div>
                            <div class="user-stats">${userPosts} posts</div>
                        </div>
                        <button class="btn btn-danger delete-user-btn" data-userid="${user.id}">
                            <i class="fas fa-trash"></i> Delete User
                        </button>
                    `;
                    usersList.appendChild(userElement);
                }
            });
            
            // 为删除用户按钮添加事件监听
            document.querySelectorAll('.delete-user-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-userid');
                    const user = users.find(u => u.id == userId);
                    if (user) {
                        userToDelete = userId;
                        deleteUserMessage.textContent = `Are you sure you want to delete user "${user.name}" (@${user.username})? This will also delete all their posts (${posts.filter(p => p.userId == userId).length} posts).`;
                        deleteUserModal.style.display = 'flex';
                    }
                });
            });
        }

        // 删除用户确认
        cancelDeleteUser.addEventListener('click', function() {
            deleteUserModal.style.display = 'none';
            userToDelete = null;
        });

        confirmDeleteUser.addEventListener('click', async function() {
            if (userToDelete) {
                // 删除用户的帖子
                posts = posts.filter(post => post.userId != userToDelete);
                // 删除用户
                users = users.filter(user => user.id != userToDelete);
                
                await savePosts();
                await saveUsers();
                renderPosts();
                renderUsersList();
                updateStats();
                deleteUserModal.style.display = 'none';
                userToDelete = null;
                showNotification('User and their posts deleted successfully', 'success');
            }
        });

        // 渲染帖子
        function renderPosts(postsToRender = posts) {
            // 清空帖子容器
            postsContainer.innerHTML = '';
            
            if (postsToRender.length === 0) {
                postsContainer.innerHTML = `
                    <div class="empty-posts">
                        <i class="fas fa-sticky-note"></i>
                        <p>No posts found. Try a different search term or create a new post!</p>
                    </div>
                `;
                return;
            }
            
            // 创建并添加帖子元素
            postsToRender.forEach(post => {
                const postElement = document.createElement('div');
                postElement.className = 'post';
                postElement.setAttribute('data-id', post.id);
                
                // 格式化日期
                const postDate = new Date(post.date);
                const formattedDate = postDate.toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
                
                // 检查当前用户是否点赞过该帖子
                const hasLiked = currentUser && post.likedBy.includes(currentUser.id);
                const likeClass = hasLiked ? 'liked' : '';
                
                // 帖子HTML
                postElement.innerHTML = `
                    ${isAdmin ? `<button class="delete-btn" data-id="${post.id}">
                        <i class="fas fa-trash"></i>
                    </button>` : ''}
                    <div class="post-header">
                        <h3 class="post-title">${escapeHtml(post.title)}</h3>
                        <span class="post-date">${formattedDate}</span>
                    </div>
                    <div class="post-content">${escapeHtml(post.content)}</div>
                    <div class="post-footer">
                        <span class="post-author">By ${escapeHtml(post.author)}</span>
                        <div class="post-actions">
                            <button class="like-btn ${likeClass}" data-id="${post.id}" ${!currentUser ? 'disabled' : ''}>
                                <i class="fas fa-thumbs-up"></i> ${post.likes}
                            </button>
                        </div>
                    </div>
                `;
                
                postsContainer.appendChild(postElement);
            });
            
            // 为删除按钮添加事件监听（仅管理员）
            if (isAdmin) {
                document.querySelectorAll('.delete-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const postId = parseInt(this.getAttribute('data-id'));
                        postToDelete = postId;
                        deletePostModal.style.display = 'flex';
                    });
                });
            }
            
            // 为点赞按钮添加事件监听
            document.querySelectorAll('.like-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const postId = parseInt(this.getAttribute('data-id'));
                    likePost(postId);
                });
            });
        }

        // 删除帖子确认
        cancelDeletePost.addEventListener('click', function() {
            deletePostModal.style.display = 'none';
            postToDelete = null;
        });

        confirmDeletePost.addEventListener('click', async function() {
            if (postToDelete) {
                posts = posts.filter(post => post.id !== postToDelete);
                await savePosts();
                renderPosts();
                updateStats();
                deletePostModal.style.display = 'none';
                postToDelete = null;
                showNotification('Post deleted successfully', 'success');
            }
        });

        // 点赞功能
        async function likePost(postId) {
            if (!currentUser) {
                showNotification('Please login to like posts', 'error');
                return;
            }
            
            const post = posts.find(p => p.id === postId);
            if (post) {
                // 检查用户是否已点赞
                const userIndex = post.likedBy.indexOf(currentUser.id);
                
                if (userIndex === -1) {
                    // 未点赞 - 添加点赞
                    post.likes++;
                    post.likedBy.push(currentUser.id);
                    showNotification('Post liked!', 'success');
                } else {
                    // 已点赞 - 取消点赞
                    post.likes--;
                    post.likedBy.splice(userIndex, 1);
                    showNotification('Like removed', 'success');
                }
                
                await savePosts();
                renderPosts();
            }
        }

        // 更新统计数据
        function updateStats() {
            // 总帖子数
            totalPostsEl.textContent = posts.length;
            
            // 今日帖子数
            const today = new Date().toDateString();
            const todayPosts = posts.filter(post => 
                new Date(post.date).toDateString() === today
            );
            todayPostsEl.textContent = todayPosts.length;
            
            // 总字符数
            const totalChars = posts.reduce((total, post) => 
                total + post.content.length, 0
            );
            totalCharsEl.textContent = totalChars.toLocaleString();
        }

        // 根据登录状态更新用户界面
        function updateUserInterface() {
            if (currentUser) {
                userInfo.style.display = 'flex';
                loginSection.style.display = 'none';
                userName.textContent = currentUser.name;
                userRole.textContent = currentUser.role;
                
                if (currentUser.role === 'admin') {
                    userRole.classList.add('admin-badge');
                    adminPanel.style.display = 'block';
                    isAdmin = true;
                } else {
                    userRole.classList.remove('admin-badge');
                    adminPanel.style.display = 'none';
                    isAdmin = false;
                }
                
                // 用户登录时隐藏作者输入框
                document.querySelector('.post-author-input').style.display = 'none';
            } else {
                userInfo.style.display = 'none';
                loginSection.style.display = 'flex';
                adminPanel.style.display = 'none';
                isAdmin = false;
                
                // 用户未登录时显示作者输入框
                document.querySelector('.post-author-input').style.display = 'block';
            }
        }

        // 显示通知
        function showNotification(message, type) {
            notification.textContent = message;
            notification.className = `notification ${type}`;
            notification.classList.add('show');
            
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }

        // 转义HTML防止注入
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 初始化页面
        async function init() {
            await loadData(); // 从IndexedDB加载数据
            renderPosts();
            updateStats();
            updateUserInterface();
        }

        // 启动应用
        init();
    </script>
</body>
</html>
